from flask import Flask, make_response, redirect, url_for, request, session, abort, g

app = Flask(__name__)
app.secret_key = 'xiaoooooooooooooooooo'


@app.route('/')
@app.route('/hello')
def index():
    name = request.args.get('name')
    if name is None:
        name = request.cookies.get('Name', 'Guest')
    return '<h1>Testing for Cookie, %s</h1>' % name


@app.route('/set/<name>')
def set_cookie(name):
    resp = make_response(redirect(url_for('index')))
    resp.set_cookie('Name', name)
    return resp

# 模拟用户认证
@app.route('/login')
def login():
    session['logged'] = True
    session['username'] = 'Xiaolei'
    return redirect(url_for('home'))


@app.route('/logout')
def logout():
    if 'logged' in session:
        session.pop('logged')
    return redirect(url_for('home'))


@app.route('/home')
def home():
    print(app.secret_key)
    print(g.xiao)
    if 'logged' not in session:
        # abort(403)
        resp = 'not login'
    else:
        resp = 'Login successful, %s' % session['username']
    return resp


@app.before_request
def get_name():
    g.xiao = 'test'


@app.teardown_appcontext
def teardownapp(exception):
    print('finished!!!')
